package io.bluerain.scripting;

import javax.script.*;

/**
 * Created by foredawn on 15-8-26.
 * jvm中的javascript引擎
 */
public class Js {

    static ScriptEngineManager manager = new ScriptEngineManager();
    static ScriptEngine engine = manager.getEngineByName("javascript");

    public static void main(String[] args) throws ScriptException {
        runJs();
        putAndGet();
        simpleBindings();
    }

    public static void runJs() {
        if (manager == null) {
            System.out.println("没有找到相关脚本引擎");
        } else {
            try {
                String js = "for(var i=0; i<10; i++){" +
                        "print(i)" +
                        "}";
                engine.eval(js);
            } catch (ScriptException e) {
                e.printStackTrace();
            }
        }
    }

    public static void putAndGet() throws ScriptException {
        engine.put("name", "小明");//参数传递
        engine.eval("var message = '已经接收到变量:' + name;");
        System.out.println(engine.get("message"));//参数获取

    }

    public static void simpleBindings() throws ScriptException {
        Bindings bindings = new SimpleBindings();
        bindings.put("age", 18);
        bindings.put("name", "小明");
        engine.eval("print(name + '今年' + age + '岁');", bindings);
//        System.out.println(engine.get("var"));无法取出脚本中的对象，进在eval中生效
    }
}
